<template>
    <div class="embroidery-uploader">

        <div class="embroidery-buttons">
            <button @click="selectFile()">上传</button>

            <!-- <ul>
                <li v-for="(item,index) in colors" :key="index">
                    <UxColorPicker name="Color" :value="getColor(item)" @input="setColor(index, $event)" />
                </li>
            </ul> -->
        </div>
        <!--
        <div class="embroidery-preview">
            <blockquote v-html="svg"></blockquote>
            <div class="canvas" ref="canvas"></div>
        </div> -->

        <!-- <canvas ref="test"></canvas> -->

        <!-- 领标编辑 -->
        <!-- <UxDialog :visible="uploader && uploader.status != 'select'" @close="cancel()">
            <div class="uploader" v-if="uploader" :error="error ? 'error' : ''">
                <h2>Upload file</h2>
                <h3 v-text="uploader.file ? uploader.file.name : 'uploading'"></h3>
                <figure>
                    <img v-if="uploader.image" :src="uploader.image.src" :style="$fiexImage(uploader.image.width,uploader.image.height,1)">
                    <UxLoading v-else />
                </figure>
                <span>
                    <em v-text="error" v-if="error"></em>
                    <em v-text="uploader.percent + '%'" v-else></em>
                </span>
                <strong>
                    <b :style="{width: uploader.percent + '%'}"></b>
                </strong>
                <button @click="cancel()">Cancel</button>
            </div>
        </UxDialog> -->
    </div>

</template>
<script>
import { readDst } from "@/utils/EmbroideryDst.js";
import { writeCanvas, writeSvg } from "@/utils/EmbroideryCanvas.js";
import { Pattern, createPattern } from "@/utils/EmbroideryPattern.js";

export default {
    data () {
        return {
            uploader: null,
            error: null,
            svg: '',
            canvas: null,
            pattern: null,
            test: {}
        };
    },

    computed: {
        colors () { return this.pattern ? this.pattern.colors : [] }
    },
    methods: {

        colorRgb (color) {
            var sColor = color.toLowerCase();
            //十六进制颜色值的正则表达式
            var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
            // 如果是16进制颜色
            if (sColor && reg.test(sColor)) {
                if (sColor.length === 4) {
                    var sColorNew = "#";
                    for (var i = 1; i < 4; i += 1) {
                        sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
                    }
                    sColor = sColorNew;
                }
                //处理六位的颜色值
                var sColorChange = [];
                for (var i = 1; i < 7; i += 2) {
                    sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
                }
                return sColorChange
            }
            return [];
        },

        getColor (color) {
            return `rgb(${[color.r, color.g, color.b].join(',')})`

        },

        setColor (index, event) {
            const rgb = this.colorRgb(event)
            this.pattern.colors[index].r = rgb[0]
            this.pattern.colors[index].g = rgb[1]
            this.pattern.colors[index].b = rgb[2]

            this.getPatternPreview(this.pattern)

            // console.log(event, this.pattern);
        },

        // 获取文件信息
        getFileToPattern (file) {


            const name = (file ? String(file.name) : '').toLowerCase()
            const type = (name.match(/\.(\w+)/) || [])[1]


            if (['emb', 'dst', 'pes', 'pec', 'exp', 'jef'].indexOf(type) < 0) {
                // 不支持的格式
                return Promise.reject('Type not provided')
            } else {
                return new Promise((resolve, reject) => {
                    const reader = new FileReader();
                    reader.onloadend = (event) => {
                        const buffer = event.target.result
                        const pattern = readDst(buffer)
                        resolve(pattern)
                        // const size = event.size;

                        // createPattern(buffer, size, type).then(res => resolve(res)).catch(err => reject(err))
                    }
                    reader.abort = (err) => reject(err);
                    reader.onerror = (err) => reject(err);
                    reader.readAsArrayBuffer(file);

                })
            }

        },



        // 预览
        getPatternPreview (pattern) {

            this.canvas = writeCanvas(pattern)
            this.svg = writeSvg(pattern)

            this.$refs.canvas.innerHTML = ''
            this.$refs.canvas.appendChild(this.canvas)

        },

        // 选中文件上传
        selectFile () {

            let filebox = document.querySelector('.filebox');
            let input = null;

            if (filebox) {
                input = filebox.querySelector('input');
            } else {
                filebox = document.createElement('div');
                filebox.setAttribute('class', 'filebox');
                filebox.setAttribute('style', ' position: absolute;left: 0;top: 0;width: 0;height: 0;overflow: hidden;opacity: 0;');
                // filebox.innerHTML = '<input type="file" accept="image/jpeg,image/jpg,image/png">';
                filebox.innerHTML = '<input type="file" >';
                document.body.appendChild(filebox);
                input = filebox.querySelector('input');
            }

            input.onchange = () => {
                if (input.files && input.files[0]) {
                    this.startUpload(input.files[0])

                    // option.file = input.files[0];
                    // let maxsize = 1024 * 1024 * 50; // 不能上传超过50M的图片
                    // if (option.file.size > maxsize) {
                    //     // 图片过大
                    //     const notify = 'The maximum upload file size is 50M.'
                    //     this.$uxMessage.error(notify);
                    //     reject(notify)
                    // } else {
                    //     resolve(option)
                    // }
                } else {
                    reject('No file select');
                }
                input.value = null;
                filebox.remove();
                // filebox.innerHTML = html;
            }

            // window.addEventListener('focus', focusEvent)
            input.click();
        },


        uploadFile (option) {

            // 先上传大图
            // 再生成缩略图

            // 文件名
            if (!option.name) {
                const time = new Date().getTime();
                const random = Math.random().toFixed(10).substr(2);
                option.name = time + "-" + random + "." + option.suffix;
            }

            // 文件路径
            if (!option.path) {
                option.path = "data/zx/design/file/"
            }

            return new Promise((resolve, reject) => {

                // 递归循环上传，最多上次3次，太多次没有作用
                let count = 3;
                let doUpload = () => {
                    const request = {
                        file: option.file,
                        name: option.name,
                        path: option.path.replace(/\/+$/, '') + '/',
                        onprogress (event) {
                            option.percent = 5 + parseInt(0.9 * event.percent);
                            option.client = event.client;
                            option.cpt = event.cpt;
                        },
                    };

                    this.$uploadToOSS(request, response => {
                        if (response.code === 0 && response.data) {
                            option.url = response.data || '';
                            resolve(option);
                        } else if (--count < 0) {
                            reject(response.msg || "Upload more than 10 times");
                        } else if (this.uploader && this.uploader == option) {
                            setTimeout(() => doUpload(), 500);
                        } else {
                            // 新的上传
                        }
                    })
                };
                doUpload();
            });
        },

        // 生成缩略图
        createThumb (option) {
            return this.$http("Drawer.createThumb", { fullname: option.url }).then((result) => {
                if (!result || result.code !== 0) {
                    return Promise.reject("Failed to create thumbnail image");
                } else {
                    option.thumb = result.data;
                    return Promise.resolve(option);
                }
            }).catch(error => {
                return Promise.reject("Failed to create thumbnail image");
            })
        },

        // 开始上传
        startUpload (file) {

            this.getFileToPattern(file).then(pattern => {
                this.$emit('upload', pattern)


                // this.pattern = pattern;
                // this.getPatternPreview(pattern)
            })


            // const option = {
            //     path: opt.path || '', // 文件保存路径
            //     name: opt.name || '', // 文件保存的名称
            //     file: null, // 文件
            //     mime: '', // 媒体类型
            //     suffix: '', // 后缀名
            //     image: null, // 预览地址
            //     percent: 5, // 上传进度
            //     url: '', // 上传完成后最终路径
            //     thumb: '', // 生成的缩略图
            //     client: null, // oss引用
            //     cpt: null, // 分片上传引用
            //     status: 'select', // 当前状态 getinfo|upload|thumb|success|error
            // }


            // this.error = null;
            // this.uploader = option;

            // // 获取文件
            // return this.selectFile(option).then(option => {
            //     // 获取图片信息
            //     return new Promise((resolve, reject) => {
            //         this.$nextTick(e => {
            //             option.status = 'getinfo';
            //             this.getFileInfo(option).then(resolve).catch(reject)
            //         })
            //     });

            // }).then(option => {

            //     // 上传图片
            //     if (this.uploader && this.uploader == option) {
            //         option.status = 'upload';
            //         return this.uploadFile(option);
            //     } else {
            //         return Promise.reject('Uploader is cancel')
            //     }

            //     // return new Promise((res, rej) => { })
            // }).then(option => {
            //     // 生成缩略图
            //     if (this.uploader && this.uploader == option) {
            //         option.status = 'thumb';
            //         return this.createThumb(option);
            //     } else {
            //         return Promise.reject('Uploader is cancel')
            //     }
            // }).then(option => {
            //     // 上传成功
            //     if (this.uploader && this.uploader == option) {
            //         option.status = 'success';
            //         callback && callback(option);
            //     } else {
            //         return Promise.reject('Uploader is cancel')
            //     }
            // }).catch(error => {

            //     if (this.uploader && this.uploader == option) {
            //         // 选择时如果不选中，则直接关闭
            //         this.error = String(error);
            //         option.status == 'select' && this.close();
            //     } else if (this.uploader) {
            //         // 有新的上传
            //     } else {
            //         this.close();
            //     }
            // })
        },

        // 取消上传
        cancel () {
            if (this.uploader && this.uploader.client && this.uploader.cpt) {
                this.uploader.client.abortMultipartUpload(this.uploader.cpt.name, this.uploader.cpt.uploadId)
                this.uploader.client = null;
                this.uploader.cpt = null;
            }
            this.close();
        },
        close () {
            this.uploader = null;
            this.error = null;
        },

        demo () {


            const str = this.$refs.stitches.innerText;

            const test = {
                left: -455,
                top: -435,
                right: 415,
                bottom: 481,
                width: 870,
                height: 916,
                colors: ["#00673e", "#b27624", "#f0f0f0", "#000000"],
                stitches: str,
            };

            // test.stitches = '0 100 0 0,100 0 0 0,200 100 0 0,100 200 0 0,0 100 0 0'
            // test.stitches = '0 100 0 0,100 0 0 0'

            const pattern = new Pattern()
            pattern.demo(test);

            const blocks = pattern.getAsBlocks().map(block => {
                const d = block.stitches.map((s, idx) => (idx == 0 ? 'M' : 'L') + s.x + ' ' + s.y)
                return `<path fill="none" stroke-width="2" stroke="${block.color}" d="${d.join(' ')}" />`
            })

            const width = pattern.right - pattern.left;
            const height = pattern.bottom - pattern.top;
            const viewbox = [pattern.left, pattern.top, width, height]
            const svg = `<svg width="${width}" height="${height}" viewBox="${viewbox}">${blocks.join('\n')}</svg>`

            this.svg = svg;

            pattern.drawShapeTo(this.$refs.test)

        }

    },
    mounted () {

        // this.demo()

    }
};
</script>
<style lang="scss" scoped>
.embroidery-uploader {
    display: flex;
    flex-direction: column;
}

.embroidery-buttons {
    ul {
        display: flex;
        flex-wrap: wrap;
    }
    li {
        width: 40px;
        height: 40px;
        display: flex;
        padding: 5px;
        span {
            width: 100%;
            height: 100%;
        }
    }
}

.embroidery-preview {
    display: flex;
    margin: 10px -10px;

    blockquote,
    .canvas {
        width: 500px;
        margin: 10px 0;
        border: 1px solid #ddd;
        margin: 0 10px;
    }
    &::v-deep canvas {
        width: 500px !important;
    }
    &::v-deep svg {
        width: 500px !important;
        height: auto !important;
    }
}

.uploader {
    z-index: 1;
    width: 368px;
    box-sizing: border-box;
    padding: 24px;
    background: #fff;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border-radius: 8px;

    & > h2 {
        font-size: 16px;
        font-family: Roboto-Medium, Roboto;
        font-weight: 500;
        color: #000000;
        line-height: 18px;
    }

    h3 {
        margin-top: 14px;
        width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        text-align: center;
        font-size: 14px;
        font-family: Roboto-Regular, Roboto;
        font-weight: 400;
        color: #000000;
        line-height: 16px;
    }

    & > figure {
        width: 100%;
        margin-top: 12px;
        position: relative;
        background: #f1f1f1;
        &::before {
            content: '';
            display: block;
            padding-bottom: 100%;
        }
        img {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
        }
    }

    & > span {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        display: block;
        text-align: center;
        font-size: 12px;
        color: #000000;
        line-height: 14px;
        height: 14px;
        margin-top: 12px;
        font-weight: normal;
        color: #000000;
    }

    & > strong {
        margin-top: 4px;
        display: block;
        width: 100%;
        height: 10px;
        border-radius: 6px;
        display: block;
        position: relative;
        background-color: #ebebeb;
        margin-top: 4px;
        b {
            position: absolute;
            left: 0;
            top: 0;
            height: 100%;
            border-radius: 6px;
            background-color: #43b9e2;
        }
    }

    button {
        width: 160px;
        margin-top: 24px;
    }

    &[error='error'] {
        & > span em {
            color: #f44336;
        }
        & > strong b {
            background-color: #f44336;
        }
    }
}
</style>
